package com.sy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sy.bean.JwtOperation;
import com.sy.constant.AppConstant;
import com.sy.dto.*;
import com.sy.entity.*;
import com.sy.exception.ShopSystemException;
import com.sy.mapper.*;
import com.sy.service.AdminService;
import com.sy.service.UserService;
import com.sy.vo.AdminPwd;
import com.sy.vo.UpdateAdmin;
import org.apache.commons.lang3.StringUtils;
import org.junit.AfterClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.sql.Date;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 管理员的服务类
 * @Author: 陈聪敏
 * @Date:
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    //用于获取认证管理器
    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;

    @Autowired
    private JwtOperation jwtOperation;

    @Autowired
    @Qualifier("cacheDetailService")
    private UserDetailsService userDetailsService;

    @Autowired(required = false)
    private HttpServletRequest req;

    @Autowired
    private UserService userService;

    @Autowired
    private AdminLoginRecordMapper adminLoginRecordMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private SortMapper sortMapper;

    /**
     * @Description: 登陆操作
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result login(String userName, String pwd, String code,String rightCode) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(userName)) {
                throw new ShopSystemException("用户名不能为空");
            }
            if (StringUtils.isBlank(pwd)) {
                throw new ShopSystemException("密码不能为空");
            }
            if (StringUtils.isBlank(code)) {
                throw new ShopSystemException("验证码不能为空");
            }
            if(!StringUtils.equalsIgnoreCase(rightCode,code)){
                throw new ShopSystemException("验证码输入错误");
            }
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            wrapper.eq("username", userName);
            Admin admin = adminMapper.selectOne(wrapper);
            if (null == admin) {
                throw new ShopSystemException("用户名不存在");
            }
            if (0 == admin.getStatus()) {
                throw new ShopSystemException("您的账户已被禁用");
            }
            //获取认证管理器
            AuthenticationManager authenticationManager = authenticationConfiguration.getAuthenticationManager();
//            System.out.println(authenticationManager);
            //用户验证:这里只需要构建一个UsernamePasswordAuthenticationToken，给定用户名和密码，验证过程由SpringSecurity完成
            //这里认证出错会出现BadCredentialsException异常，捕获处理即可
            //这里的校验逻辑大致为：
            // encoder.matches("明文密码","数据库中存储的密码")，因此数据库存储的应该是加密密码，否则无法校验
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(userName, pwd));
//            User user = userMapper.findUserByUserName(userName);
            //存储认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
            //获取认证通过的具体用户信息,可用于生成JWT
            //由于这里返回的类型是自己写的基于缓存的用户提供者总获取的
            //返回的用户类型是实现了UserDetails后自己扩展的TokenUser类型
            TokenUser userDetails = (TokenUser) userDetailsService.loadUserByUsername(userName);
            //创建JWT
            String token = jwtOperation.createJwt(userDetails);
            result.setCode(200);
            //密码在返回给前端用户时置为空
            userDetails.setPassword(null);
            //登录成功返回用户基本信息以及Token
            Map<String, Object> data = new LinkedHashMap<String, Object>() {{
                put("token", token);
                put("userInfo", userDetails);
            }};

            AdminLoginRecord adminLoginRecord = new AdminLoginRecord();
            adminLoginRecord.setAid(admin.getId());
            adminLoginRecord.setAddress("宁波");
            adminLoginRecord.setIp("127.0.0.1");
            adminLoginRecord.setContent("登录成功");
            Date date = new Date(new java.util.Date().getTime());
            adminLoginRecord.setLogintime(date);
            adminLoginRecordMapper.insert(adminLoginRecord);
            result.setData(data);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(401);
            result.setError(e.getMessage());
        } catch (BadCredentialsException e) {
            //当用户认证过程中用户名和密码如果有错，抛出BadCredentialsException异常
            e.printStackTrace();
            result.setCode(401);
            result.setError("账号密码错误");
            //如果第一次登陆失败且当前使用的用户名是数据库存在的用户名
            //就在redis中添加一个key，名为login_max_try_count_+用户名，并且设置这个键过期时间为30，初始值为1

            //如果不是第一次出现错误，则则对当前用户的login_max_try_count_+用户名 对应键自增1
            //如果不存在，在表示第一次出现错误，则重新在redis中添加一个key，名为login_max_try_count_+用户名，并且设置这个键过期时间为30，初始值为1

        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError("服务端异常");
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            wrapper.eq("username", userName);
            Admin admin = adminMapper.selectOne(wrapper);
            if (null != admin) {
                AdminLoginRecord adminLoginRecord = new AdminLoginRecord();
                adminLoginRecord.setAid(admin.getId());
                adminLoginRecord.setAddress("宁波");
                adminLoginRecord.setIp("127.0.0.1");
                adminLoginRecord.setContent("登录失败");
                Date date = new Date(new java.util.Date().getTime());
                adminLoginRecord.setLogintime(date);
                adminLoginRecordMapper.insert(adminLoginRecord);
            }
        }
        return result;
    }

    /**
     * @Description: 获取登录管理员权限信息
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result getLoginAdmin() {
        Result result = new Result();
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            TokenUser tokenUser = (TokenUser) userDetailsService.loadUserByUsername(authentication.getName());
            tokenUser.setPassword(null);
            result.setCode(200);
            result.setData(tokenUser);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 通过id获取权限名称
     * @Author: 陈聪敏
     * @Date:
     */
    public String getRoleName(Integer aid) {
        QueryWrapper<AdminRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("aid", aid);
        AdminRole adminRole = adminRoleMapper.selectOne(queryWrapper);
        Role role = roleMapper.selectById(adminRole.getRoleId());
        return role.getDescs();
    }

    /**
     * @Description: 获取登录管理员具体信息
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result getLoginAdminInfo() {
        Result result = new Result();
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            TokenUser tokenUser = (TokenUser) userDetailsService.loadUserByUsername(authentication.getName());
            Integer aid = tokenUser.getUid();
            Admin admin = adminMapper.selectById(aid);
            String descs = getRoleName(aid);
            LoginAdminInfo loginAdminInfo = new LoginAdminInfo();
            loginAdminInfo.setUserName(admin.getUserName());
            loginAdminInfo.setAge(admin.getAge());
            loginAdminInfo.setPhone(admin.getPhone());
            loginAdminInfo.setEmail(admin.getEmail());
            loginAdminInfo.setQq(admin.getQq());
            loginAdminInfo.setRole(descs);
            loginAdminInfo.setSex(admin.getSex());
            loginAdminInfo.setRegtime(admin.getRegtime());
            result.setCode(200);
            result.setData(loginAdminInfo);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 更新管理员信息
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result updateAdmin(UpdateAdmin updateAdmin) {
        Result result = new Result();
        try {
            System.out.println(updateAdmin);
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            TokenUser tokenUser = (TokenUser) userDetailsService.loadUserByUsername(authentication.getName());
            Integer aid = tokenUser.getUid();
            String userName = updateAdmin.getUserName();
            Integer age = updateAdmin.getAge();
            Integer sex = updateAdmin.getSex();
            String phone = updateAdmin.getPhone();
            String qq = updateAdmin.getQq();
            String email = updateAdmin.getEmail();
            if (StringUtils.isBlank(userName)) {
                throw new ShopSystemException("用户名不能为空");
            }
            if (null == adminMapper.selectById(aid)) {
                throw new ShopSystemException("此用户名已存在");
            }
            if (null == age) {
                throw new ShopSystemException("年龄不能为空");
            }
            if (age < 0 || age > 100) {
                throw new ShopSystemException("请输入正常的年龄");
            }
            if (null == sex) {
                throw new ShopSystemException("性别不能为空");
            }
            if (StringUtils.isBlank(phone)) {
                throw new ShopSystemException("手机号不能为空");
            }
            if (!phone.matches(AppConstant.PHONE_REGEXP)) {
                throw new ShopSystemException("请输入正确的手机格式");
            }
            if (StringUtils.isBlank(qq)) {
                throw new ShopSystemException("qq不能为空");
            }
            if (StringUtils.isBlank(email)) {
                throw new ShopSystemException("电子邮件不能为空");
            }
            if (!email.matches(AppConstant.EMAIL_REGEXP)) {
                throw new ShopSystemException("请输入正确的邮箱格式");
            }
            Admin admin = new Admin();
            admin.setId(aid);
            admin.setUserName(userName);
            admin.setAge(age);
            admin.setSex(sex);
            admin.setPhone(phone);
            admin.setQq(qq);
            admin.setEmail(email);
            adminMapper.updateById(admin);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 更新管理员密码
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result updateAdminPwd(AdminPwd adminPwd) {
        Result result = new Result();
        try {
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            TokenUser tokenUser = (TokenUser) userDetailsService.loadUserByUsername(authentication.getName());
            Integer aid = tokenUser.getUid();
            String pwd = adminPwd.getPwd();
            String newPwd = adminPwd.getNewPwd();
            String confirmPwd = adminPwd.getConfirmPwd();
            if (StringUtils.isBlank(pwd)) {
                throw new ShopSystemException("旧密码不能空");
            }
            if (!encoder.matches(pwd, tokenUser.getPassword())) {
                throw new ShopSystemException("旧密码不正确");
            }
            if (StringUtils.isBlank(newPwd)) {
                throw new ShopSystemException("新密码不能空");
            }
            if (StringUtils.isBlank(confirmPwd)) {
                throw new ShopSystemException("确认密码不能空");
            }
            if (!StringUtils.equals(newPwd, confirmPwd)) {
                throw new ShopSystemException("新密码和确认密码必须相同");
            }
            if (encoder.matches(adminPwd.getNewPwd(), tokenUser.getPassword())) {
                throw new ShopSystemException("对不起，你输入的新旧密码不能相同");
            }
            Admin admin = new Admin();
            admin.setId(aid);
            admin.setPwd(encoder.encode(newPwd));
            adminMapper.updateById(admin);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 获取所有管理员登录的信息
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result getAdminLoginInfo() {
        Result result = new Result();
        try {
            List<AdminLoginRecordTable> adminLoginRecords = new ArrayList<>();
            List<Admin> admins = adminMapper.selectList(null);
            for (Admin admin : admins) {
                Integer aid = admin.getId();
                String roleName = getRoleName(aid);
                QueryWrapper<AdminLoginRecord> wrapper = new QueryWrapper<>();
                wrapper.eq("aid", aid);
                List<AdminLoginRecord> adminLoginRecordList = adminLoginRecordMapper.selectList(wrapper);
                for (AdminLoginRecord adminLoginRecord:adminLoginRecordList) {
                    AdminLoginRecordTable adminLoginRecordTable = new AdminLoginRecordTable();
                    adminLoginRecordTable.setId(aid);
                    adminLoginRecordTable.setRole(roleName);
                    adminLoginRecordTable.setUserName(admin.getUserName());
                    adminLoginRecordTable.setContent(adminLoginRecord.getContent());
                    adminLoginRecordTable.setAddress(adminLoginRecord.getAddress());
                    adminLoginRecordTable.setIp(adminLoginRecord.getIp());
                    adminLoginRecordTable.setLogintime(adminLoginRecord.getLogintime());
                    adminLoginRecords.add(adminLoginRecordTable);
                }
            }
            result.setCode(200);
            result.setData(adminLoginRecords);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 获得所有管理员信息
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result getAllAdmin() {
        Result result = new Result();
        try {
            List<Admin> admins = adminMapper.selectList(null);
            List<AdminInfo> adminInfos = new ArrayList<>();
            for (Admin admin : admins) {
                AdminInfo adminInfo = new AdminInfo();
                adminInfo.setId(admin.getId());
                adminInfo.setEmail(admin.getEmail());
                adminInfo.setPhone(admin.getPhone());
                adminInfo.setRegtime(admin.getRegtime());
                String role = getRoleName(admin.getId());
                adminInfo.setRole(role);
                adminInfo.setUserName(admin.getUserName());
                adminInfo.setStatus(admin.getStatus());
                adminInfos.add(adminInfo);
            }
            result.setCode(200);
            result.setData(adminInfos);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 通过用户和添加时间获取用户的信息
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result getAdminByCondition(String keyword, String times) {
        Result result = new Result();
        try {
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            if(!StringUtils.isBlank(keyword)){
                wrapper.eq("username",keyword);
            }
            if(!StringUtils.isBlank(times)){
                wrapper.eq("regtime",times);
            }
            List<Admin> admins = adminMapper.selectList(wrapper);
            List<AdminInfo> adminInfos = new ArrayList<>();
            for (Admin admin : admins) {
                AdminInfo adminInfo = new AdminInfo();
                adminInfo.setId(admin.getId());
                adminInfo.setEmail(admin.getEmail());
                adminInfo.setPhone(admin.getPhone());
                adminInfo.setRegtime(admin.getRegtime());
                String role = getRoleName(admin.getId());
                adminInfo.setRole(role);
                adminInfo.setUserName(admin.getUserName());
                adminInfo.setStatus(admin.getStatus());
                adminInfos.add(adminInfo);
            }
            result.setCode(200);
            result.setData(adminInfos);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    @Override
    public Result getAdmins() {
        Result result = new Result();
        try {
            QueryWrapper<AdminRole> superWrapper = new QueryWrapper<>();
            superWrapper.eq("rid",1);
            QueryWrapper<AdminRole> wrapper = new QueryWrapper<>();
            wrapper.eq("rid",2);
            QueryWrapper<AdminRole> editWrapper = new QueryWrapper<>();
            editWrapper.eq("rid",3);
            List<AdminRole> superAdmins = adminRoleMapper.selectList(superWrapper);
            List<AdminRole> admins = adminRoleMapper.selectList(wrapper);
            List<AdminRole> editAdmins = adminRoleMapper.selectList(editWrapper);
            Integer superAdminSize = 0;
            Integer adminSize = 0;
            Integer editAdminSize = 0;
            if(!CollectionUtils.isEmpty(superAdmins)){
                superAdminSize=superAdmins.size();
            }
            if(!CollectionUtils.isEmpty(admins)){
                adminSize=admins.size();
            }
            if(!CollectionUtils.isEmpty(editAdmins)){
                editAdminSize=editAdmins.size();
            }
           AdminSize adminSizes = new AdminSize();
            adminSizes.setSurperAdmin(superAdminSize);
            adminSizes.setAdmin(adminSize);
            adminSizes.setEditAdmin(editAdminSize);
            adminSizes.setTotal(superAdminSize+adminSize+editAdminSize);
            result.setCode(200);
            result.setData(adminSizes);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 禁用管理员
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result memberStop(Integer id) {
        Result result = new Result();
        try {
            Admin admin = new Admin();
            admin.setId(id);
            admin.setStatus(0);
            adminMapper.updateById(admin);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 启用管理员
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result memberStart(Integer id) {
        Result result = new Result();
        try {
            Admin admin = new Admin();
            admin.setId(id);
            admin.setStatus(1);
            adminMapper.updateById(admin);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 删除管理员
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    @Transactional
    public Result delAdmin(String ids) {
        Result result = new Result();
        try {
            String[] idsInfo = ids.split(",");
            List<Integer> idList = new ArrayList<>();
            for (int i = 0; i < idsInfo.length; i++) {
                idList.add(Integer.parseInt(idsInfo[i]));
            }
            List<Admin> admins = adminMapper.selectBatchIds(idList);
            for (Admin admin : admins) {
                UpdateWrapper<AdminRole> wrapper = new UpdateWrapper<>();
                wrapper.eq("aid", admin.getId());
                adminRoleMapper.delete(wrapper);
            }
            adminMapper.deleteBatchIds(idList);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 获取所有用户的权限信息
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    public Result getAdminRights() {
        Result result = new Result();
        try {
            List<Admin> admins = adminMapper.selectList(null);
//            String superIds = "";
//            String generalIds = "";
//            String editIds = "";
            String superRole = "";
            String generalRole = "";
            String editRole = "";
            Integer superPeople=0;
            Integer generalPepple=0;
            Integer editPeople = 0;
            String superName="";
            String genName="";
            String editName="";
            List<AdminRights> adminRightsList = new ArrayList<>();
            for (Admin admin : admins) {
                String role = getRoleName(admin.getId());
                if (StringUtils.equals("超级管理员",role)) {
//                    superIds+=","+admin.getId();
                    superName+=","+admin.getUserName();
                    superPeople++;
                }
                if (StringUtils.equals("普通管理员",role)) {
//                    generalIds+=","+admin.getId();
                    genName+=","+admin.getUserName();
                    generalPepple++;
                }
                if (StringUtils.equals("编辑管理员",role)) {
//                    editIds+=","+admin.getId();
                    editName+= ","+admin.getUserName();
                    editPeople++;
                }
            }
//            superIds = superIds.substring(1);
//            generalIds = generalIds.substring(1);
//            editIds = editIds.substring(1);
            if(!StringUtils.isBlank(superName)){
                superName = superName.substring(1);
                AdminRights adminRights = new AdminRights();
                adminRights.setId(1);
                adminRights.setRole("超级管理员");
                adminRights.setUsername(superName);
                adminRights.setPeoplenum(superPeople);
                adminRights.setDescs("拥有至高无上的权利,操作系统的所有权限");
                adminRightsList.add(adminRights);
            }
            if(!StringUtils.isBlank(genName)){
                genName = genName.substring(1);
                AdminRights genAdminRights = new AdminRights();
                genAdminRights.setId(2);
                genAdminRights.setRole("普通管理员");
                genAdminRights.setUsername(genName);
                genAdminRights.setPeoplenum(generalPepple);
                genAdminRights.setDescs("拥有网站的系统大部分使用权限，没有权限管理功能。");
                adminRightsList.add(genAdminRights);
            }
            if(!StringUtils.isBlank(editName)){
                editName = editName.substring(1);
                AdminRights editAdminRights = new AdminRights();
                editAdminRights.setId(3);
                editAdminRights.setRole("编辑管理员");
                editAdminRights.setUsername(editName);
                editAdminRights.setPeoplenum(editPeople);
                editAdminRights.setDescs("拥有部分权限，主要进行编辑功能，无边界订单功能，权限分配功能。");
                adminRightsList.add(editAdminRights);
            }
            System.out.println(adminRightsList);
            result.setCode(200);
            result.setData(adminRightsList);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 群删管理员
     * @Author: 陈聪敏
     * @Date:
     */
    @Override
    @Transactional
    public Result batchDelAdmin(String ids) {
        Result result = new Result();
        try {
            String[] idsInfo = ids.split(",");
            List<Integer> idList = new ArrayList<>();
            for (int i = 0; i < idsInfo.length; i++) {
                Integer rid = Integer.parseInt(idsInfo[i]);
                QueryWrapper<AdminRole> wrapper = new QueryWrapper<>();
                wrapper.eq("rid",rid);
                UpdateWrapper<AdminRole> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("rid",rid);
                List<AdminRole> adminRoles = adminRoleMapper.selectList(wrapper);
                for (AdminRole adminRole:adminRoles) {
                    Integer aid = adminRole.getUserId();
                    adminMapper.deleteById(aid);
                }
                adminRoleMapper.delete(updateWrapper);
            }
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    @Override
    public Result getArticle() {
        Result result = new Result();
        try {
           List<Article> articles = articleMapper.selectList(null);
            result.setCode(200);
            result.setData(articles);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    @Override
    public Result getSort() {
        Result result = new Result();
        try {
            List<Sort> sorts = sortMapper.selectList(null);
            result.setCode(200);
            result.setData(sorts);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 获取所有的用户信息
     * @return
     * @ Author 孙玮立
     */
    @Override
    public Result getUsers() {
        Result result = new Result();
        try {
            result = userService.getUsers();
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }
    /**
     * 获取所有的等级信息
     * @return
     * @ Author 孙玮立
     */
    @Override
    public Result getLevelCount() {
        Result result = new Result();
        try {
            result = userService.getLevelCount();
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

}
